<template>
  <view>
    <view class="addr-container">
       <view v-if="address.userName" class="addr-box">
          <view class="addr-info">
            <text>{{address.userName}}</text>
            <text>{{address.telNumber}}</text>
          </view>
          <view class="detail">{{addrDetail}}</view>
       </view>
       <button v-else @click="chooseAddr"> + 添加收获地址</button>
    </view>
    <view>
      <!-- 从这里触发获取用户信息事件 -->
      <button open-type="getUserInfo" @getuserinfo="getUserInfo">获取token</button>
    </view>
    <view class="cart-container">
       <view class="cart-item" v-for="(item,index) in goodsList" :key="index">
         <view class="pic">
           <image :src="item.goods_small_logo"></image>
         </view>
         <view class="desc">
           <view class="title">{{item.goods_name}}</view>
           <view class="calc-box">
             <view class="price">￥{{item.goods_price}}</view>
             <view class="count-box">
                <view class="val">x<text>{{item.count}}</text></view>
             </view>
           </view>
         </view>
       </view>
    </view>
    <view class="btm-tool">
      <view class="total-box">
        <view class="total-price">
          <text>合计</text>
          ￥{{totalPrice}}
        </view>
        <view class="yun">包含运费</view>
      </view>
      <view class="settle">支付({{allCheckTypes}})</view>
    </view>
  </view>
</template>

<script>
export default {
   data(){
     return{
        goodsList:[],
        address:{}
     }
   },
   watch:{
      goodsList:{
        deep:true,
        handler(newCarts){
          //  每次有修改缓存数据的处理
          uni.setStorageSync('carts', newCarts);
        } 
      }
   },
   computed:{
       addrDetail(){
         return (
           this.address.provinceName + 
           this.address.cityName + 
           this.address.countyName + 
           this.address.detailInfo
         );
       },
       allCheckTypes(){
          return this.goodsList.filter(v=>v.checked).length;
       },
       totalPrice(){
         let total = 0;
          this.goodsList.forEach(item => {
              if(item.checked){
                  total += item.goods_price * item.count;
              }
          });
          return total;
       }
     },
   methods:{
     chooseAddr(){
       //微信的方法，选择地址  
       uni.chooseAddress({
          success:result => {
            console.log(result);
            this.address = result
          }
       })
     },
     async getUserInfo(e){
       //从用户信息接口中获取支付整个环节需要的参数
       const { encryptedData, rawData, iv, signature } = e.detail;
       //console.log(encryptedData, rawData, iv, signature);

       //调用微信的登录接口 获取code 微信小程序的临时凭据
       const {code} = (await uni.login())[1];
        
       //获取后台token 为什么这里需要重新token
       const {token} = await this.request({
         url:'/users/wxlogin',
         method:'post',
         data:{ encryptedData, rawData, iv, signature, code }
       })
       console.log(333);

      //构建生成订单的参数
      const orderData = {
        // 总价格
        order_price:this.totalPrice,
        // 收货地址
        consignee_addr: this.addrDetail,
        // 订单数组
        goods:this.goodsList.map(cart => {
            return{
              goods_id:cart.goods_id,
              goods_number:cart.count,
              goods_price:cart.goods_price
            }
        })
      };


       //生成订单
       const {order_number} = await this.request({
          url: "/my/orders/create",
          method: "post",
          data:orderData,
          header:{
             Authorization: token
          }
       });  

      //发送订单编号，获取支付的参数
      const {pay} = await this.request({
          url:'/my/orders/req_unifiedorder',
          method:'post',
          data:{order_number},
          header:{
            Authorization: token
          }
       });

       // 发送pay支付参数 完成调起 微信支付!!!
       await uni.requestPayment(pay);

       //查询订单状态
       const res = await this.request({
          url: "/my/orders/chkOrder",
          data: { order_number },
          method: "post",
          header:{
            Authorization: token
          }
       });

       uni.showToast({ title: "支付成功" });
     }
   },
   onLoad(){
     let goods = uni.getStorageSync('carts') || [];
     console.log(goods);
     this.goodsList = goods.filter(v=>v.checked);
     this.address = uni.getStorageSync("address") || {};
   }
}
</script>

<style lang="scss">
view.addr-container {
  border-bottom:1px solid #c0c0c0;
  .addr-box{
    padding:20rpx;
    .addr-info{
      display:flex;
      justify-content: space-between;
      margin-bottom: 10rpx;
    }
    .detail{

    }
  }
  button {
    margin: 50rpx auto;
    width:340rpx;
    height:60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
    border:1px solid $theme-color;
    background-color: #F8F8F8;
  }
}

.cart-container {
  padding-bottom: 90rpx;
  .cart-item {
    display: flex;
    justify-content: center;
    padding:20rpx;
    padding-left: 0;
    border-bottom:1px solid #c0c0c0;
    .pic{
      flex:2;
      image {
        height:200rpx;
      }
    }
    .desc {
      flex:3;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding:20rpx 0;
      .title {
        padding-left: 20rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        /* 弹性伸缩盒子模型显示 */
        display: -webkit-box;
        /* 限制在一个块元素显示的文本的行数 */
        -webkit-line-clamp: 2;
        /* 设置或检索伸缩盒对象的子元素的排列方式 */
        -webkit-box-orient: vertical;
        // 拆散单词
        word-break: break-all;

      }
      .calc-box {
        display: flex;
        justify-content: space-between;
        padding:0 10rpx;
        .price {
          font-size: 32rpx;
          color: $theme-color;
        }
        .count-box{
          display: flex;
          align-items: center;
          .val{
            font-size: 32rpx; 
            text{
               padding-left: 6rpx;
            }
          }
        }
      }
    }
  }
}
.btm-tool {
  position: fixed;
  left:0;
  bottom:0;
  width:100vw;
  height:90rpx;
  display: flex;
  border:1px solid #c0c0c0;
  background-color: #fff;
  checkbox-group {
    flex:1;
    display: flex;
    justify-content: center;
    align-items: center;
    checkbox {

    }
  }

  .total-box {
    flex:1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-end;
    padding-right: 20rpx;
    .total-price {
       font-size: 32rpx;
       color: $theme-color;
       text{
         color: #000;
       }
    }
    view {

    }
  }

  .settle {
    flex:1;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: $theme-color;
    font-size: 32rpx;
    color: #fff;
  }
}
</style>